/* 
 * Context.js
 * Copyright Jacob Kelley
 * MIT License
 *
 * 文档
 * http://www.jq22.com/yanshi322
 */

var context = context || (function () {
    var global_count = 0 ;
	var options = {
		fadeSpeed: 100,
		filter: function ($obj) {
			// Modify $obj, Do not return
		},
		above: 'auto',
		preventDoubleContext: true,
		compress: false
	};

    function closeAll() {
        $('.databasetm-menu').fadeOut(options.fadeSpeed, function(){
            $('.databasetm-menu').css({display:'none'}).find('.drop-left').removeClass('drop-left');
        });
    }

	function initialize(opts) {
		
		options = $.extend({}, options, opts);
		
		$(document).on('click', 'html', function () {
            closeAll();
		});
		if(options.preventDoubleContext){
			$(document).on('contextmenu', '.databasetm-menu', function (e) {
				e.preventDefault();
			});
		}
		$(document).on('mouseenter', '.dropdown-submenu', function(){
			var $sub = $(this).find('.dropdown-context-sub:first'),
				subWidth = $sub.width(),
				subLeft = $sub.offset().left,
				collision = (subWidth+subLeft) > window.innerWidth;
			if(collision){
				$sub.addClass('drop-left');
			}
		});
		
	}

	function updateOptions(opts){
		options = $.extend({}, options, opts);
	}

	function buildMenu(data, id, subMenu) {
		var subClass = (subMenu) ? ' dropdown-context-sub' : '',
			compressed = options.compress ? ' compressed-context' : '',
			$menuContainer = $('<div class="databasetm-menu" id="dropdown-' + id + '"></div>'),
			$menu = $('<ul class="box_cmenu" ></ul>');
        $menuContainer.append($menu);

        var linkTarget = '';
        for(var i = 0; i<data.length; i++) {
            var dataOne = data[i];
            if (typeof dataOne.divider !== 'undefined') {
				$menu.append('<li class="divider"></li>');
			} else if (typeof dataOne.header !== 'undefined') {
				$menu.append('<li class="nav-header">' + dataOne.header + '</li>');
			} else {
				if (typeof dataOne.href == 'undefined') {
					dataOne.href = '#';
				}
				if (typeof dataOne.target !== 'undefined') {
					linkTarget = ' target="'+dataOne.target+'"';
				}
				if (typeof dataOne.subMenu !== 'undefined') {
					$sub = ('<li class="dropdown-submenu"><a tabindex="-1" href="' + dataOne.href + '">' + dataOne.text + '</a></li>');
				} else {
					$sub = $('<li class="cursorlist clearfix">' +
                        '<span class="'+dataOne.cls+' fl"></span><span class="hrefTxt fl">' +dataOne.text+
                        '</span></li>');
				}
				if (typeof dataOne.action !== 'undefined') {
					var actiond = new Date(),
						actionID = 'event-' + actiond.getTime() * Math.floor(Math.random()*100000),
						eventAction = dataOne.action;

					$sub.find('.hrefTxt').attr('id', actionID);
					$('#' + actionID).addClass('context-event');


                    //delegate -> not delegate
                    // console.log($sub.find('a'));
                    $sub.click(function (e) {
                    // $sub.find('span:eq(0)').click(function (e) {
                    //     console.log($(this).hasClass("nocursorlist"));
                    //     console.log($(this));
                        if($(this).hasClass("nocursorlist")) {
                            //block
                            e.stopPropagation();
                            e.preventDefault();
                            return ;
                        }

                        var _inner_data = $(this).data("_data");

                        _inner_data.action(e);

                        if(options.actionPostProcessor){
                            options.actionPostProcessor();
                        }
                    });
				}
				//控制绘制样式 只会调用一次
                if (typeof dataOne.decorator !== 'undefined') {
                    var $newLi = dataOne.decorator($sub);
                    if($newLi){
                        $sub = $newLi;
                    }
                }

                $sub.data("_data",dataOne);

				$menu.append($sub);

				if (typeof dataOne.subMenu != 'undefined') {
					var subMenuData = buildMenu(dataOne.subMenu, id, true);
					$menu.find('li:last').append(subMenuData);
				}
			}
			if (typeof options.filter == 'function') {
				options.filter($menu.find('li:last'));
			}
		}
		return $menuContainer;
	}

	function addContext(selector, data,decoratorFunc,positionConf) {
		var d = new Date(),
			id = d.getTime()+"-"+global_count++,
			$menu = buildMenu(data, id);
			
		$('body').append($menu);
        // if (selector == ".mainContainer"){
        //     console.log("addContext.");
        //     console.log(arguments);
        //     console.log($menu);
        // }
		
		$(document).on('contextmenu', selector, function (e) {
			e.preventDefault();
			e.stopPropagation();
            //save event place
            context.target = e.target;

            // console.log(e);

            //多选状态下
            //右击已选中的nothing
            //右击未选中的则清除所有已选中
            //此时菜单位置应该在图标正右方
            var $target = $(e.target);
            // console.log($target);
            var closestIcon = $target.closest(".icotop-span");
            if(closestIcon.length==0){
                //右键点击更名区域时
                closestIcon=$target.parents(".editdatanameinput_div").prev(".icotop-span");
            }

            //不是上一步文件夹
            var isPrevDir = closestIcon.children().hasClass("prev");

            //添加选中样式
            if(!closestIcon.hasClass("selected") && !isPrevDir){
                _multiSelection.clearMultiSelection();
                closestIcon.addClass("selected");
            }


			$('.databasetm-menu:not(.dropdown-context-sub)').hide();
			
			$dd = $('#dropdown-' + id);

            //修改每一条样式
            //每次弹出菜单都会调用
            if(decoratorFunc && typeof decoratorFunc == 'function' ){
                var isContinue = decoratorFunc($dd,function (iterFunc) {
                    $dd.find("li").each(function (i,ele) {
                        var $li = $(ele);
                        iterFunc($li,$li.data("_data"));
                    });
                });


                if(!isContinue){
                    return;
                }
            }

            var defaultPositionNormal =function (mouseX,mouseY,$menuCom,$target) {
                return {
                    top: mouseY + 10,
                    // left: e.pageX - 13
                    left: mouseX + 15
                };
            }

            var defaultPositionUp =function (mouseX,mouseY,$menuCom,$target) {
                var autoH = $menuCom.height() + 12;
                return {
                    top: mouseY - 20 - autoH,
                    left: mouseX - 13
                };
            }


            if(positionConf){
                if(positionConf.positionNormal){
                    defaultPositionNormal=positionConf.positionNormal;
                }
                if(positionConf.positionUp){
                    defaultPositionUp=positionConf.positionUp;
                }
            }

            //show
			if (typeof options.above == 'boolean' && options.above) {
				$dd.addClass('dropdown-context-up').css({
					top: e.pageY - 20 - $('#dropdown-' + id).height(),
					left: e.pageX - 13
				}).fadeIn(options.fadeSpeed);
			} else if (typeof options.above == 'string' && options.above == 'auto') {
				$dd.removeClass('dropdown-context-up');

				var autoH = $dd.height() + 12;
                //position:up
				if ((e.pageY + autoH) > $('html').height()) {
					$dd.addClass('dropdown-context-up').css(defaultPositionUp(e.pageX, e.pageY,$dd,$target)).fadeIn(options.fadeSpeed);
				} else {
                    //position:custom default:left-bottom

					$dd.css(defaultPositionNormal(e.pageX, e.pageY,$dd,$target)).fadeIn(options.fadeSpeed);
				}
			}


		});
	}
	
	function destroyContext(selector) {
		$(document).off('contextmenu', selector).off('click', '.context-event');
	}
	
	return {
		init: initialize,
		settings: updateOptions,
		attach: addContext,
		destroy: destroyContext,
        closeAll: closeAll
	};
})();